const router = require('koa-router')()
const fs = require('fs')
const path = require('path');
const config = require('../public/javascripts/config');
router.prefix('/upload');


router.get('/', (ctx,next)=>{
  ctx.body = JSON.stringify(ctx)
})

/**
 * post 上传文件请求
 * 提供html网页的form表单
 */
router.post('/',(ctx,next)=>{
  // 获取请求中的文件流
  const file = ctx.request.files.file;
  // 读文件流
  const fileReader = fs.createReadStream(file.path)
  // 拼存放的文件目录
  const filePath = path.join(__dirname,'../apk');
  // 绝对路径  
  const fileResource = filePath + `/${config.apkName}`;

  /*
   使用 createWriteStream 写入数据，然后使用管道流pipe拼接
  */
  const writeStream = fs.createWriteStream(fileResource);

  ctx.type = 'html';
  const uploadSuccessUrl = path.join(__dirname,'../public/html/uploadSuccess.html')

 if(!fs.existsSync(filePath)){
   fs.mkdir(filePath,(err)=>{
     if(err){
       console.log(err.message)
      throw new Error(err)
     }else{
      fileReader.pipe(writeStream);
      ctx.body= fs.createReadStream(uploadSuccessUrl)
      //  ctx.body = {
      //    url:uploadUrl+`/${file.name}`,
      //    code:0,
      //    message:'上传成功'
      //  }
     }
   })
 }else{
  fileReader.pipe(writeStream);
  ctx.body= fs.createReadStream(uploadSuccessUrl)
  //  ctx.body={
  //   url:uploadUrl+`/${file.name}`,
  //   code:0,
  //   message:'上传成功'
  //  }
 }

})

module.exports=router;